import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Scanner;

public class 神奇闹钟 {
    public static void main(String[] args) {

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        Scanner scan = new Scanner(System.in);
        int n = scan.nextInt();
        String str[] = new String[n];
        scan.nextLine();
        for (int i = 0; i < n; i++) {
            str[i] = scan.nextLine();
        }
        //格式化输入的日期
        for (int i = 0; i < n; i++) {
            String[] times = str[i].split(" ");
            LocalDateTime ldt = LocalDateTime.parse(times[0] + " " + times[1], formatter);
            ldt = ldt.withSecond(0);
            //计算距离纪元时间多少秒
            long time = ldt.toEpochSecond(ZoneOffset.UTC);
            //将x转为秒单位
            int xSecond = Integer.parseInt(times[2]) * 60;
            //关键步骤：找出最近的倍数秒
            while (time % xSecond != 0) {
                time -= 60;//回退1分钟
            }
            //格式化输出
            ldt = LocalDateTime.ofEpochSecond(time, 0, ZoneOffset.UTC);
            System.out.println(ldt.format(formatter));
        }
    }
}
